<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商家" prop="mid" >
        <el-select v-model="queryParams.mid" placeholder="请选择商家id" style="width: 150px;" clearable>
          <el-option
            v-for="dict in sys_job_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="start">
        <el-date-picker clearable
          v-model="queryParams.start"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="end">
        <el-date-picker clearable
          v-model="queryParams.end"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['coupon:coupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['coupon:coupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['coupon:coupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['coupon:coupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="优惠券发放者" align="center" prop="source">
        <template #default="scope">
          <dict-tag :options="yyq_coupon_issuer" :value="scope.row.source"/>
        </template>
      </el-table-column>
      <el-table-column label="商家" align="center" prop="mid">
        <template #default="scope">
          <dict-tag :options="sys_job_status" :value="scope.row.mid"/>
        </template>
      </el-table-column>
      <el-table-column label="优惠券名称" align="center" prop="name" />
      <el-table-column label="优惠券类型" align="center" prop="type"/>
      <el-table-column label="折扣" align="center" prop="discount" />
      <el-table-column label="触发金额" align="center" prop="triggerMoney" />
      <el-table-column label="优惠金额" align="center" prop="preferentialMoney" />
      <el-table-column label="开始时间" align="center" prop="start" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.start, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="end" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.end, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="投放数量" align="center" prop="num" />
      <el-table-column label="领取数量" align="center" prop="size" />
      <el-table-column label="状态" align="center" prop="status" >
        <template #default="scope">
          <dict-tag :options="sys_job_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['coupon:coupon:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['coupon:coupon:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="couponRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="优惠券发放者" prop="source">
          <el-select v-model="form.source" placeholder="请选择优惠券发放者">
            <el-option
              v-for="dict in yyq_coupon_issuer"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商家id" prop="mid" v-show="form.source === 1">
          <el-select v-model="form.mid" placeholder="请选择商家id【如果是平台优惠券，可以为null】">
            <el-option
              v-for="dict in sys_job_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券名称" prop="name">
          <!-- <el-input v-model="form.name" placeholder="请输入优惠券名称" /> -->
          <el-select v-model="form.name" placeholder="请选择优惠券名称">
            <el-option
              v-for="dict in youhui_name"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type" v-show="form.source === 1 || form.name === '节假日优惠券'">
          <el-select v-model="form.type" placeholder="请选择优惠券类型【满减券、折扣券】">
            <el-option
              v-for="dict in youhui_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 动态显示折扣输入框 -->
        <el-form-item label="折扣" prop="discount" v-if="form.type === '折扣券'">
          <el-input v-model="form.discount" placeholder="请输入折扣 【如果是打折券，则有折扣】" />
        </el-form-item>
        <!-- 动态显示触发金额和优惠金额输入框 -->
        <el-form-item label="触发金额" prop="triggerMoney" v-if="form.type === '满减券' || form.name === '新用户优惠券'">
          <el-input v-model="form.triggerMoney" placeholder="请输入触发金额 【如果是满减，最低金额】" />
        </el-form-item>
        <el-form-item label="优惠金额" prop="preferentialMoney" v-if="form.type === '满减券' || form.name === '新用户优惠券'">
          <el-input v-model="form.preferentialMoney" placeholder="请输入优惠金额【如果是满减，减的金额】" />
        </el-form-item>
        <el-form-item label="开始时间" prop="start" v-show="form.source === 1 || form.name === '节假日优惠券'">
          <el-date-picker clearable
            v-model="form.start"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end" v-show="form.source === 1 || form.name === '节假日优惠券'">
          <el-date-picker clearable
            v-model="form.end"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="投放数量" prop="num" v-show="form.source === 1 || form.name === '节假日优惠券'">
          <el-input v-model="form.num" placeholder="请输入投放数量" />
        </el-form-item>
        <el-form-item label="领取数量" prop="size" v-show="form.source === 1 || form.name === '节假日优惠券'">
          <el-input v-model="form.size" placeholder="请输入领取数量【固定死，每人限领1张】" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Coupon">
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon } from "@/api/coupon/coupon"

const { proxy } = getCurrentInstance()
const { sys_job_status,yyq_coupon_issuer } = proxy.useDict('sys_job_status','yyq_coupon_issuer')

const couponList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const youhui_type = ref([
  { label: '折扣券', value: '折扣券' },
  { label: '满减券', value: '满减券' }
])
const youhui_name = ref([
  { label: '新用户优惠券', value: '新用户优惠券' },
  { label: '节假日优惠券', value: '节假日优惠券' },
  { label: '商家优惠券', value: '商家优惠券' } 
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    mid: null,
    name: null,
    start: null,
    end: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询优惠券列表 */
function getList() {
  loading.value = true
  listCoupon(queryParams.value).then(response => {
    couponList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    source: null,
    mid: null,
    name: null,
    type: null,
    discount: null,
    triggerMoney: null,
    preferentialMoney: null,
    start: null,
    end: null,
    num: null,
    size: null,
    status: null
  }
  proxy.resetForm("couponRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加优惠券"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCoupon(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改优惠券"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除优惠券编号为"' + _ids + '"的数据项？').then(function() {
    return delCoupon(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('coupon/coupon/export', {
    ...queryParams.value
  }, `coupon_${new Date().getTime()}.xlsx`)
}

getList()
</script>
